var zTree;
var mygrid;

$(document).ready(function () {
    mygrid = new dhtmlXGridObject('userList');
    mygrid.setImagePath(getRootPath() + "/resources/plugin/dhtmlx/dhtmlxGrid/codebase/imgs/");
    mygrid.setHeader("序号,姓名,账号,用户部门,性别,操作");
    mygrid.setInitWidths("100,*,*,*,*,350");
    mygrid.setColTypes("ro,ro,ro,ro,ro,ro");
    mygrid.setColAlign("center,center,center,center,center,center");
    mygrid.setSkin("tdh_simple");
    mygrid.enableTooltips("false,false,false,false,false,false");

    mygrid.pagingLayout("count,first,prev,page,next,last,limit,refresh,skip");
    mygrid.pagingLimits("30,40,50");
    mygrid.enablePagingon(true, 40);
    mygrid.setPageCurrent(0);
    mygrid.init();
    zTree = $.fn.zTree;

    myAjax({
        url: '/departTree.do',
        mySuccess: function (res) {
            var zNodes = [
                {id: 1, pId: 0, name: "部门", open: true, iconSkin: "courtIcon"}
            ];
            var setting = {
                callback: {
                    onClick: zTreeOnClick,
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                }
            };
            res.data.forEach(function (value) {
                zNodes.push(
                    {id: 11, pId: 1, name: value.bmmc, bmdm: value.bmdm, iconSkin: "courtIcon"}
                );
            });
            zTree.init($('#test'), setting, zNodes)
        }
    })
    showUserList();
})

function doUpload(yhdm) {
    $("#yhdm").val(yhdm);
    layer.load(1);
    $('#uploadAvatar').submit();
}

function doSearch() {
    var text = $('input[id="idText"]').val();
    var data = {"type": "search", "param": trim(text)};
    zTree.getZTreeObj('test').cancelSelectedNode();
    showUserList(this, data);
}

function doAdd() {
    openLayer("add");
}

function doUpdate(yhdm) {
    openLayer("update", yhdm);
}

function doShow(yhdm) {
    openLayer("show", yhdm);
}

function doDelete(yhdm) {
    layer.confirm("确认删除么", {title: "确认提示"}, function (index) {
        myAjax({
            url: "/delete.do",
            type: "post",
            data: {"yhdm": yhdm},
            mySuccess: function (res) {
                layer.msg(res.msg);
                if (res.code === 1) {
                    if (mygrid.pageTotal == 1) {
                        showUserList();
                    } else {
                        if (parseInt(mygrid.pageTotal) % mygrid.pageLimit == 1 && mygrid.pageTotal > mygrid.pageLimit) {
                            mygrid.pageStart = mygrid.pageStart - mygrid.pageLimit;
                        }
                        mygrid.loadPage(true);
                    }
                }
            }
        })
    })
}

function doLogout() {
    layer.confirm("确定要退出么？", {title: "确认提示"}, function () {
        myAjax({
            url: '/logout.do',
            mySuccess: function (res) {
                layer.msg(res.msg);
                window.location.href = getRootPath();
            }
        })
    })
}

function zTreeOnClick(event, treeId, treeNode) {
    var data = {"param": treeNode.bmdm, "type": treeNode.bmdm ? "bmdm" : ''};
    showUserList(this, data);
}

function showUserList(obj, data) {
    data = data || {};
    var param = data.param || '';
    var type = data.type || '';

    // mygrid.loadXML(getRootPath() + "/xmlUserList.do?type=" + encodeStr(type) + "&param=" + encodeStr(param), myGridCallBack);
    mygrid.loadXML(getRootPath() + "/xmlJspUserList.do?type=" + encodeStr(type) + "&param=" + encodeStr(param), function () {
        if (type || param) {
            if (mygrid.pageTotal == 0) {
                layer.alert("没有用户哦", function (index) {
                    showUserList();
                    layer.close(index);
                })
            }
        }
    });
}

function myGridCallBack(isHome) {

}

function openLayer(type, yhdm) {
    yhdm = yhdm || '';
    myAjax({
        url: '/userInfo.do',
        data: {"type": type, "yhdm": yhdm},
        dataType: 'html',
        mySuccess: function (res) {
            var btn = ["保存", "关闭"];
            var shadeClose = (type === "show");
            if (type === "show") {
                btn.shift();
            }
            layer.open({
                type: 1,
                id: "userInfo",
                area: ["800px", "340px"],
                shadeClose: shadeClose,
                content: res,
                btn: btn,
                success: function () {
                    if (type !== "add") {
                        layer.load(2);
                        setSelVal($('#yhxb'), $('#hiddenYhxb').val());
                        setSelVal($('#yhbm'), $('#hiddenYhbm').val());
                        layer.closeAll("loading");
                    }
                },
                yes: function (index, layerno) {
                    if (type === "show") {
                        layer.close(index);
                        return;
                    }
                    //口令一致性检查
                    var password = trim($(layerno).find('#yhkl').val());
                    var repeatPassword = trim($(layerno).find('#cfkl').val());
                    if (password && repeatPassword && password !== repeatPassword) {
                        layer.alert("用户口令与重复口令不一致，请检查！", {
                            icon: 2,
                        });
                        return;
                    }
                    //必填项检查
                    var msg = verify($(layerno).find('form'));
                    if (msg.length) {
                        layer.alert("请检查必填项：" + msg.join(","), {
                            icon: 2,
                        });
                        return;
                    }
                    //非法字符串检查
                    var yhid = $(layerno).find('#yhid').val();
                    if (yhid.indexOf("admin") > -1) {
                        layer.alert("用户ID不可包含admin！");
                        return;
                    }
                    //校验通过
                    var isUpdate = (type === "update");
                    var json = $(layerno).find('form').serializeJson();
                    json["sfjy"] = json.sfjy || '0';
                    json["sfjy"] = json.sfjy === 'on' ? '1' : '0';
                    json["yhdm"] = isUpdate ? yhdm : "320100" + json.yhid;
                    myAjax({
                        url: '/insertOrUpdate.do?isUpdate=' + isUpdate,
                        type: "post",
                        data: JSON.stringify(json),
                        contentType: "application/json",
                        mySuccess: function (res) {
                            layer.msg(res.msg);
                            if (res.code === 1) {
                                layer.close(index);
                                if (!isUpdate) {
                                    mygrid.loadXML(getRootPath() + "/xmlJspUser.do?yhdm=" + encodeStr(json["yhdm"]));
                                } else {
                                    mygrid.loadPage(true);
                                }
                            }
                        }
                    })
                }
            })
        }
    })
}